<template>
  <div :style="{ width, height }" id="echarts-wrap"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, onUnmounted, watch } from 'vue';

const props = defineProps({
  width: { type: String, default: '100%' },
  height: { type: String, default: '100%' },
  options: { type: Object, default: null }
})

let myChart = null;

watch(() => props.options, (newVal) => {
  disposeEchart();
  createEchart();
})

onMounted(() => {
  createEchart();
})

//  销毁时，清除缓存数据
onUnmounted(() => {
  disposeEchart();
})

const createEchart = () => {
  // 基于准备好的dom，初始化echarts实例
  const myChart = echarts.init(document.getElementById('echarts-wrap'));
  // 绘制图表
  props.options && myChart.setOption(props.options);
}

const disposeEchart = () => {
  if (myChart) {
    myChart.dispose();
    myChart = null;
  }
}
</script>

<style lang="scss" scoped></style>